package com.kenliang.javase.concurrent;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author KenLiang
 * @description:
 * @date Created in 4:33 PM 2020/5/25.
 */
public class UnsafeTest {



    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        Field unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
        unsafeField.setAccessible(true);
        Unsafe unsafe =(Unsafe) unsafeField.get(null);
        Class clazz= Target.class;
        Field[] declaredFields = clazz.getDeclaredFields();
        for(Field field:declaredFields){
            System.out.println(field.getName()+":"+unsafe.objectFieldOffset(field));
        }
        Target target = new Target();
        System.out.println(target.intParam);
        System.out.println(unsafe.compareAndSwapInt(target,12,30,4));
        System.out.println(target.intParam);
        System.out.println(unsafe.compareAndSwapInt(target,12,3,4));
        System.out.println(target.intParam);

        System.out.println(target.strParam);
        System.out.println(unsafe.compareAndSwapObject(target,24,null,"newStrParam"));
        System.out.println(target.strParam);

        System.out.println(target.strParam2);
        System.out.println(unsafe.compareAndSwapObject(target,28,"strParam2","newStrParam2"));
        System.out.println(target.strParam2);

        System.out.println(target.strParam3);
        System.out.println(unsafe.compareAndSwapObject(target,32,"strParam3","newStrParam3"));
        System.out.println(target.strParam3);
        //strParam2,strParam3证明了 new String("strParam3")是申明了一个新的对象，内存地址不一样
    }
}
class Target{
    int intParam=3;
    long longParam;
    String strParam;
    String strParam2="strParam2";
    String strParam3=new String("strParam3");
}

